package com.shadow.baiqun.delegate.receive.pregoods;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.rey.material.app.DatePickerDialog;
import com.rey.material.app.Dialog;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.ThemeManager;
import com.shadow.baiqun.R;
import com.shadow.baiqun.R2;
import com.shadow.baiqun.config.ItemField;
import com.shadow.baiqun.delegate.receive.adapter.GoodsListAdapter;
import com.shadow.baiqun.delegate.receive.goodscheck.CheckDelegate;
import com.shadow.baiqun.delegate.receive.goodsscan.GoodsScanDelegate;
import com.shadow.baiqun.delegate.receive.locationcheck.LocationCheckDelegate;
import com.shadow.baiqun.delegate.receive.sendorder.SendOrderDelegate;
import com.shadow.baiqun.delegate.receive.upload.UploadFileDelegate;
import com.shadow.baiqun.view.TableHeadView;
import com.shadow.core.delegate.RxShadowDelegate;
import com.shadow.core.event.StartBrotherFragmentEvent;
import com.shadow.core.net.callback.IError;
import com.shadow.core.net.callback.ISuccess;
import com.shadow.core.net.rx.RxRestClient;
import com.shadow.ui.recycler.BaseDecoration;
import com.shadow.ui.recycler.MultipleItemEntity;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author zy
 * on 2018/5/19
 * 预收货列表
 */
public class GoodsListDelegate extends RxShadowDelegate {

    public static GoodsListDelegate create() {
        final GoodsListDelegate contentDelegate = new GoodsListDelegate();
        final Bundle bundle = new Bundle();
        contentDelegate.setArguments(bundle);
        return contentDelegate;
    }

    private static final int PAGE_SIZE = 50;
    @BindView(R2.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R2.id.swipe_layout)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R2.id.lv_title)
    TableHeadView mHeadView;
    @BindView(R2.id.btn_choose_date)
    TextView mButton;
    @BindView(R2.id.iv_date_clear)
    ImageView mIvClear;

    @BindView(R2.id.et_supplier_name)
    EditText mEtSupplierName;
    @BindView(R2.id.et_supplier_code)
    EditText mEtSupplierCode;
    private GoodsListAdapter mAdapter;
    private int mNextRequestPage = 1;
    private boolean isRequesting = false;

    @Override
    public Object setLayout() {
        return R.layout.delegate_pre_receive_goods;
    }


    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        initView();
    }


    private void initView() {
        List<String> list = new ArrayList<>();
        list.add("供应商名称");
        list.add("发货时间");
        list.add("状态");
        list.add("用途");
        mHeadView.setHeaders(list);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
        mAdapter = new GoodsListAdapter(getContext(), null, R.layout.item_pre_goods);

        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadMore();
            }
        }, mRecyclerView);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.addItemDecoration(BaseDecoration.create(getContext().getResources()
                .getColor(R.color.color_white_light_gray), 1));
        mRecyclerView.addItemDecoration(BaseDecoration.create(getContext().getResources().getColor(R.color.color_white_light_gray),
                1));
        mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                final MultipleItemEntity multipleItemEntity = (MultipleItemEntity) adapter.getItem(position);
                PreGoodsEntry preGoodsEntry;
                if (multipleItemEntity != null) {
                    preGoodsEntry = multipleItemEntity.getField(ItemField.ITEM_OBJ);
                    final String status = preGoodsEntry.getPrepgoodsStatus();
                    final int orderId = preGoodsEntry.getPrepgoodsId();
                    if ("0".equals(status) || "-1".equals(status)) {
                        EventBus.getDefault().post(new StartBrotherFragmentEvent(CheckDelegate.create(orderId, 0)));
                    } else if ("3".equals(status)) {
                        //收货完成
                        new CompleteDialog(getContext(), new CompleteDialog.OnActionListener() {
                            @Override
                            public void onOrderComplete() {
                                EventBus.getDefault().post(new StartBrotherFragmentEvent(SendOrderDelegate.create(orderId)));
                            }

                            @Override
                            public void onOrderDetail() {
                                //收货单核对
                                EventBus.getDefault().post(new StartBrotherFragmentEvent(CheckDelegate.create(orderId, 1)));
                            }
                        }).show();
                    } else if ("4".equals(status)) {
                        new PauseDialog(getContext(), new PauseDialog.OnActionListener() {
                            @Override
                            public void onOrderComplete() {
                                //货物归为
                                EventBus.getDefault().post(new StartBrotherFragmentEvent(GoodsScanDelegate.create(orderId)));
                            }

                            @Override
                            public void onOrderDetail() {
                                //查看收货单
                                EventBus.getDefault().post(new StartBrotherFragmentEvent(CheckDelegate.create(orderId, 1)));
                            }
                        }).show();
                    } else if ("5".equals(status)) {
                        EventBus.getDefault().post(new StartBrotherFragmentEvent(CheckDelegate.create(orderId, 2)));
                    } else if ("6".equals(status)) {
                        //待上传送货单
                        EventBus.getDefault().post(new StartBrotherFragmentEvent(UploadFileDelegate.create(orderId)));
                    } else {
                        //1 2
                        new OperationDialog(getContext(), new OperationDialog.OnActionListener() {
                            @Override
                            public void onCheckLocation() {
                                //库位核对
                                EventBus.getDefault().post(new StartBrotherFragmentEvent(LocationCheckDelegate.create(orderId)));
                            }

                            @Override
                            public void onBackHome() {
                                //货物归位
                                EventBus.getDefault().post(new StartBrotherFragmentEvent(GoodsScanDelegate.create(orderId)));
                            }

                            @Override
                            public void onOrderDetail() {
                                EventBus.getDefault().post(new StartBrotherFragmentEvent(CheckDelegate.create(orderId, 1)));
                            }
                        }).show();
                    }
                }
            }
        });
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setEmptyView(R.layout.view_loading, mRecyclerView);
        if (mAdapter.getEmptyView() != null) {
            mAdapter.getEmptyView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    refresh();
                }
            });
        }
    }

//    @Override
//    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
//        super.onLazyInitView(savedInstanceState);
//        refresh();
//    }

    private void loadMore() {
        requestData(false);
    }

    private void setData(boolean isRefresh, List<MultipleItemEntity> data) {
        mNextRequestPage++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mAdapter.setNewData(data);
        } else {
            if (size > 0) {
                mAdapter.addData(data);
            }
        }
        if (size < PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(isRefresh);
        } else {
            mAdapter.loadMoreComplete();
        }
    }

    //刷新
    private void refresh() {
        if (!isRequesting) {
            mNextRequestPage = 1;
            isRequesting = true;
            mAdapter.setEmptyView(R.layout.view_loading, mRecyclerView);
            requestData(true);
        }
    }

    private void requestData(final boolean isRefresh) {
        mDisposables.add(RxRestClient.builder()
                .url("WMS/backstage/collectgoods/getCollectGoodsList")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        mAdapter.setEmptyView(R.layout.view_empty, mRecyclerView);
                        ReceiveGoodsConverter converter = new ReceiveGoodsConverter();
                        converter.setJsonData(response);
                        ArrayList<MultipleItemEntity> itemEntities = converter.convert();
                        setData(isRefresh, itemEntities);
                        isRequesting = false;
                        mRefreshLayout.setRefreshing(false);
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mAdapter.setEmptyView(R.layout.view_empty, mRecyclerView);
                        isRequesting = false;
                        mRefreshLayout.setRefreshing(false);
                    }
                })
                .params("sendtime", "请选择发货日期".equals(mButton.getText().toString()) ? "" : mButton.getText())
                .params("suppname", mEtSupplierName.getText().toString())
                .params("suppcode", mEtSupplierCode.getText().toString())
                .params("page", mNextRequestPage)
                .params("rows", PAGE_SIZE)
                .build()
                .unRestPost());
    }

    @OnClick(R2.id.btn_choose_date)
    public void onChooseDate() {
        Dialog.Builder builder;
        boolean isLightTheme = ThemeManager.getInstance().getCurrentTheme() == 0;
        builder = new DatePickerDialog.Builder(isLightTheme ? R.style.Material_App_Dialog_DatePicker_Light : R.style.Material_App_Dialog_DatePicker) {
            @Override
            public void onPositiveActionClicked(DialogFragment fragment) {
                DatePickerDialog dialog = (DatePickerDialog) fragment.getDialog();
                String date = dialog.getFormattedDate(new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA));
                mButton.setText(date);
                mIvClear.setVisibility(View.VISIBLE);
                super.onPositiveActionClicked(fragment);
            }

            @Override
            public void onNegativeActionClicked(DialogFragment fragment) {
                super.onNegativeActionClicked(fragment);
            }
        };
        builder.positiveAction("确定")
                .negativeAction("取消")
        ;
        DialogFragment fragment = DialogFragment.newInstance(builder);
        fragment.show(getFragmentManager(), null);
    }

    @OnClick(R2.id.tv_search)
    public void onSearch() {
        if (!isFastClick()) {
            refresh();
        }
    }


    @OnClick(R2.id.iv_date_clear)
    public void onDateClear() {
        mButton.setText("请选择发货日期");
        mIvClear.setVisibility(View.GONE);
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        refresh();
    }

}
